/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IDE_formularios;

import ConexaoDados.InteracaoDados;
import OPC.LeituraThread;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javafish.clients.opc.JOpc;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Igor
 */
public class Avaliacao extends javax.swing.JFrame {
    private LeituraThread conexao[] = new LeituraThread[20];
    private int i=1;
    private DefaultTableModel modeloTabela;
    private String [] dadosServidor;

    /**
     * Creates new form Avaliacao
     */
    public Avaliacao() throws SQLException {
        initComponents();
        AtualizaListaServidor();
    }
    
    private void AtualizaListaServidor() throws SQLException{
        
        InteracaoDados dados = new InteracaoDados();
        ResultSet result_serv;
        result_serv = dados.consulta("select * from servidor_opc");
        
        while(result_serv.next())
        {
           cbnome_servidor.addItem(result_serv.getInt(1)+" - "+result_serv.getString(2)+" - "+result_serv.getString(3)+" - "+result_serv.getString(4)+" - "+result_serv.getBoolean(5)+" - "+result_serv.getInt(6)+" - "+result_serv.getInt(7)); 
            
        }
        result_serv.close();
        
        
        
    }
    private String getDateTime() 
    {
        DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy 'às' HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
     private void addservidorConectado() {
         
        Object[] listLinha = new Object[8];
        modeloTabela = (DefaultTableModel) jTblServidoresConectados.getModel();
        listLinha[0] = dadosServidor[2].trim();
        listLinha[1] = dadosServidor[1].trim();
        listLinha[2] = dadosServidor[3].trim();
        listLinha[3] = dadosServidor[6].trim()+" Horas";        
        listLinha[4] = dadosServidor[5].trim() +" ms";
        listLinha[5] = getDateTime().toString();
        if(Boolean.parseBoolean(dadosServidor[4].trim()) == true)
        {
            listLinha[6] = "On";
        }        
        else
            listLinha[6] = "Off";   
        
        listLinha[7] = i;
        
        modeloTabela.addRow(listLinha);
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbnome_servidor = new javax.swing.JComboBox();
        btnIniciarLeitura = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTblServidoresConectados = new javax.swing.JTable();
        jBtnDesconectar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Programa de Teste - UFRN - Programa rascunho");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Leitura OPC", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BELOW_TOP, new java.awt.Font("Tahoma", 1, 14))); // NOI18N

        jLabel1.setText("Servidor");

        cbnome_servidor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Escolha um Servidor Para Conexão." }));
        cbnome_servidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbnome_servidorActionPerformed(evt);
            }
        });

        btnIniciarLeitura.setText("Iniciar");
        btnIniciarLeitura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIniciarLeituraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addComponent(cbnome_servidor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnIniciarLeitura, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addContainerGap(536, Short.MAX_VALUE)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbnome_servidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnIniciarLeitura))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(12, 12, 12)
                    .addComponent(jLabel1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Servidores Conectados", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BELOW_TOP, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        jPanel1.setToolTipText("Servidores Conectados por Thread");

        jTblServidoresConectados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Host", "Nome", "No", "T. Avaliação", "T. Amostragem", "Conectado", "Registro", "Indice"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTblServidoresConectados);

        jBtnDesconectar.setText("Parar");
        jBtnDesconectar.setToolTipText("Desconectar");
        jBtnDesconectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnDesconectarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 718, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jBtnDesconectar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jBtnDesconectar))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(22, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-758)/2, (screenSize.height-374)/2, 758, 374);
    }// </editor-fold>//GEN-END:initComponents

    private void cbnome_servidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbnome_servidorActionPerformed

        
        
        
        
        
        
        
    }//GEN-LAST:event_cbnome_servidorActionPerformed

    private void btnIniciarLeituraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarLeituraActionPerformed
      
        
        if (cbnome_servidor.getSelectedIndex()>0)
        {
            dadosServidor = cbnome_servidor.getSelectedItem().toString().split("-");
            
            if(Boolean.parseBoolean(dadosServidor[4].trim())==true){
            
            
            InteracaoDados dados = new InteracaoDados();
            List<String> listTags = new ArrayList();

            
            try {
                    ResultSet result_tags;

                    result_tags = dados.consulta("select * from associatag where servidoropc_fk="+Integer.parseInt(dadosServidor[0].trim())+"");
                    while(result_tags.next())
                        {                            
                        listTags.add(result_tags.getString("NomeTag"));
                        }
                    result_tags.close();
                } 
            catch (SQLException ex) 
                {
                    java.util.logging.Logger.getLogger(Avaliacao.class.getName()).log(Level.SEVERE, null, ex);
                }
            JOpc.coInitialize();
            
            conexao[i] = new LeituraThread();                           
            conexao[i].IniciaLeituraTags(listTags, dadosServidor[1].trim(), dadosServidor[2].trim(), dadosServidor[3].trim(), Integer.parseInt(dadosServidor[5].trim()), Integer.parseInt(dadosServidor[6].trim()), Integer.parseInt(dadosServidor[0].trim()));
            addservidorConectado();
            listTags.clear();
            i++;
            if(i>=19)
            {
            i=1;
                }    
            }  
        }
    }//GEN-LAST:event_btnIniciarLeituraActionPerformed

    private void jBtnDesconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnDesconectarActionPerformed
        int linhaSelecionada = jTblServidoresConectados.getSelectedRow();
        
        if (linhaSelecionada != -1) 
            {            
                conexao[Integer.parseInt(modeloTabela.getValueAt(linhaSelecionada, 7).toString())].pararThread();   
                System.out.println("Avaliação do servidor: "+modeloTabela.getValueAt(linhaSelecionada, 1).toString().trim()+" Foi encerrada com sucesso!");
                modeloTabela.removeRow(linhaSelecionada);

            } 
        else 
            {
                JOptionPane.showMessageDialog(rootPane, "Escolha um servidor para ser desconectado");
            }
    }//GEN-LAST:event_jBtnDesconectarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Avaliacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Avaliacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Avaliacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Avaliacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Avaliacao().setVisible(true);
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger(Avaliacao.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIniciarLeitura;
    private javax.swing.JComboBox cbnome_servidor;
    private javax.swing.JButton jBtnDesconectar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTblServidoresConectados;
    // End of variables declaration//GEN-END:variables
}
